package com.gaohc.framework.web.service;

import com.gaohc.common.constant.Constants;
import com.gaohc.common.core.redis.RedisUtil;
import com.gaohc.system.sysmenu.ISysMenuService;
import com.gaohc.system.sysuser.ISysRoleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户权限处理
 * 
 * @author ruoyi
 */
@Component
public class SysPermissionService
{
    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取角色数据权限
     * 
     * @param userId 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(Long userId)
    {
        Set<String> roles = new HashSet<>();
        String key = Constants.LOGIN_ROLE_KEY+userId;
        if (redisUtil.hasKey(key)) {
            roles = (Set<String>)redisUtil.get(key);
        } else {
            if (userId != null && 1L == userId)
            {
                roles.add("admin");
            }
            else
            {
                roles.addAll(roleService.selectRolePermissionByUserId(userId));
            }
            redisUtil.set(key, roles);
        }

        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param userId 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(Long userId)
    {
        Set<String> perms = new HashSet<>();
        String key = Constants.LOGIN_MENU_KEY+userId;
        if (redisUtil.hasKey(key)) {
            perms = (Set<String>)redisUtil.get(key);
        } else {
            if (userId != null && userId == 1L)
            {
                perms.add("*:*:*");
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(userId));
            }
            redisUtil.set(key, perms);
        }
        // 管理员拥有所有权限

        return perms;
    }
}
